package 面试.基础题.二分查找;

/**
 * 二分查找
 *
 * @author codex
 * @since 2021-10-03
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] array = {1, 5, 8, 11, 19, 22, 31, 35, 40, 45, 48, 49, 50};
        int target = 22;
        int i = binarySearch(array, target);
        System.out.println(i);
    }
    
    public static int binarySearch(int[] arr, int target) {
        int l = 0, r = arr.length - 1;
        while (l <= r) {
            int mid = (l + r) >>> 1;
            if (arr[mid] == target) {
                return mid;
            }
            
            if (arr[mid] > target) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        
        return -1;
    }
}
